#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>
#include "Logger.hpp"

void Remind(const std::string &name)
{
    std::cerr << "使用方法：" << name << " 端口号" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Remind(argv[0]);
        exit(1);
    }
    int _fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (_fd < 0)
    {
        LOG(LogLevel::FATAL) << "socket创建失败";
        exit(2);
    }
    LOG(LogLevel::INFO) << "socket创建成功";

    uint16_t port=std::stoi(argv[2]);
    std::string ip=argv[1];
    struct sockaddr_in local;
    bzero(&local, sizeof(local));
    local.sin_family=AF_INET;
    local.sin_port=htons(port);
    local.sin_addr.s_addr=inet_addr(ip.c_str());
    while(true)
    {
        std::cout<<"请输入你要翻译的单词：";
        std::string line;
        std::getline(std::cin,line);

        sendto(_fd,line.c_str(),line.size(),0,(struct sockaddr*)&local,sizeof(local));

        struct sockaddr_in temp;
        socklen_t len=sizeof(temp);
        char buffer[1024];
        buffer[0]=0;
        int n=recvfrom(_fd,buffer,sizeof(buffer),0,(struct sockaddr*)&temp,&len);
        if(n>0)
        {
            buffer[n]=0;
            std::cout<<buffer<<std::endl;
        }
    }
    return 0;
};